/**
 * @file AIClassification.vue
 * @description AI智能分类标签功能页面
 * @created 2024-03-20
 */

<template>
  <div class="ai-classification">
    <div class="page-header">
      <h2>AI智能分类标签</h2>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section">
      <div 
        class="upload-area" 
        @click="triggerFileInput"
        @dragover.prevent="isDragging = true"
        @dragleave.prevent="isDragging = false"
        @drop.prevent="handleFileDrop"
        :class="{ 'is-dragging': isDragging, 'is-loading': isProcessing }"
      >
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileSelected"
          accept=".doc,.docx,.ppt,.pptx,.pdf,.txt,.mp4,.mp3"
        />
        
        <template v-if="isProcessing">
          <el-progress type="circle" :percentage="uploadProgress" />
          <p>处理中...{{ processingStatus }}</p>
        </template>
        <template v-else>
          <span class="icon">📁</span>
          <h3>拖拽文件到此处或点击上传</h3>
          <p>支持 DOC、PPT、PDF、MP4 等多种格式</p>
        </template>
      </div>
    </div>

    <!-- 分类结果展示 -->
    <div class="classification-results" v-if="classificationResults.length > 0">
      <h3>智能分类结果</h3>
      <div class="result-cards">
        <div class="result-card" v-for="result in classificationResults" :key="result.id">
          <div class="file-info">
            <span class="file-icon">{{ getFileIcon(result.fileName) }}</span>
            <div class="file-details">
              <h4>{{ result.fileName }}</h4>
              <p>{{ formatFileSize(result.fileSize) }}</p>
            </div>
          </div>
          <div class="tags-section">
            <div class="tag" v-for="tag in result.tags" :key="tag.name"
                 :style="{ background: tag.confidence > 0.8 ? '#e6f7ff' : '#fff7e6' }">
              {{ tag.name }} ({{ (tag.confidence * 100).toFixed(0) }}%)
              <span class="delete-tag" @click="removeTag(result, tag)">×</span>
            </div>
            <div class="add-tag" @click="showAddTagDialog(result)">+</div>
          </div>
          <div class="actions">
            <button class="edit-btn" @click="editClassification(result)">编辑标签</button>
            <button class="confirm-btn" @click="confirmClassification(result)">确认分类</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加标签对话框 -->
    <el-dialog 
      v-model="addTagDialogVisible" 
      title="添加标签" 
      width="30%"
    >
      <el-form :model="newTagForm">
        <el-form-item label="标签名称">
          <el-input v-model="newTagForm.name" placeholder="请输入标签名称"></el-input>
        </el-form-item>
        <el-form-item label="置信度">
          <el-slider v-model="newTagForm.confidence" :step="0.05" :min="0" :max="1" show-stops></el-slider>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addNewTag">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { classifyDocument } from '@/api/admin/dify'

// 文件拖拽上传相关状态
const fileInput = ref(null)
const isDragging = ref(false)
const isProcessing = ref(false)
const uploadProgress = ref(0)
const processingStatus = ref('')

// 新标签表单
const addTagDialogVisible = ref(false)
const newTagForm = reactive({
  name: '',
  confidence: 0.8
})
const currentEditingResult = ref(null)

// 分类结果数据
const classificationResults = ref([])

/**
 * 触发文件输入框点击
 */
const triggerFileInput = () => {
  if (!isProcessing.value) {
    fileInput.value.click()
  }
}

/**
 * 处理文件选择事件
 * @param {Event} event - 文件选择事件
 */
const handleFileSelected = (event) => {
  const files = event.target.files
  if (files.length > 0) {
    processFile(files[0])
  }
}

/**
 * 处理文件拖放事件
 * @param {DragEvent} event - 拖放事件
 */
const handleFileDrop = (event) => {
  isDragging.value = false
  const files = event.dataTransfer.files
  if (files.length > 0) {
    processFile(files[0])
  }
}

/**
 * 处理文件上传和AI分类
 * @param {File} file - 上传的文件
 */
const processFile = async (file) => {
  try {
    isProcessing.value = true
    processingStatus.value = '准备文件...'
    
    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += 10
        
        if (uploadProgress.value < 30) {
          processingStatus.value = '上传文件...'
        } else if (uploadProgress.value < 60) {
          processingStatus.value = '分析文件内容...'
        } else {
          processingStatus.value = '生成智能标签...'
        }
      }
    }, 500)
    
    // 调用Dify API进行文件分类
    const fileData = { file }
    const response = await classifyDocument(fileData)
    
    // 处理成功
    clearInterval(progressInterval)
    uploadProgress.value = 100
    processingStatus.value = '处理完成'
    
    // 添加到结果列表
    const result = {
      id: Date.now(),
      fileName: file.name,
      fileSize: file.size,
      tags: response.tags || [
        // 这里是备用数据，实际应用中应使用response中的数据
        { name: '数学', confidence: 0.92 },
        { name: '教学资源', confidence: 0.88 },
        { name: response.mainCategory || '课件', confidence: 0.85 }
      ],
      rawFile: file
    }
    
    classificationResults.value.unshift(result)
    
    ElNotification({
      title: '分类成功',
      message: `文件"${file.name}"已成功分类`,
      type: 'success'
    })
    
    // 重置状态
    setTimeout(() => {
      isProcessing.value = false
      uploadProgress.value = 0
      fileInput.value.value = '' // 清空文件输入框
    }, 1000)
  } catch (error) {
    ElMessage.error(`文件处理失败: ${error.message || '未知错误'}`)
    isProcessing.value = false
    uploadProgress.value = 0
  }
}

/**
 * 获取文件图标
 * @param {string} fileName - 文件名
 * @returns {string} 对应的文件图标
 */
const getFileIcon = (fileName) => {
  const extension = fileName.split('.').pop().toLowerCase()
  const iconMap = {
    doc: '📝',
    docx: '📝',
    ppt: '📊',
    pptx: '📊',
    pdf: '📄',
    txt: '📃',
    mp4: '🎬',
    mp3: '🎵'
  }
  
  return iconMap[extension] || '📁'
}

/**
 * 格式化文件大小
 * @param {number} size - 文件大小（字节）
 * @returns {string} 格式化后的文件大小
 */
const formatFileSize = (size) => {
  if (size < 1024) {
    return `${size} B`
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`
  } else {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`
  }
}

/**
 * 移除标签
 * @param {Object} result - 分类结果对象
 * @param {Object} tag - 要移除的标签
 */
const removeTag = (result, tag) => {
  const index = result.tags.findIndex(t => t.name === tag.name)
  if (index !== -1) {
    result.tags.splice(index, 1)
  }
}

/**
 * 显示添加标签对话框
 * @param {Object} result - 当前编辑的分类结果
 */
const showAddTagDialog = (result) => {
  currentEditingResult.value = result
  newTagForm.name = ''
  newTagForm.confidence = 0.8
  addTagDialogVisible.value = true
}

/**
 * 添加新标签
 */
const addNewTag = () => {
  if (!newTagForm.name.trim()) {
    ElMessage.warning('标签名称不能为空')
    return
  }
  
  // 检查标签是否已存在
  if (currentEditingResult.value.tags.some(tag => tag.name === newTagForm.name)) {
    ElMessage.warning('标签已存在')
    return
  }
  
  // 添加新标签
  currentEditingResult.value.tags.push({
    name: newTagForm.name,
    confidence: newTagForm.confidence
  })
  
  addTagDialogVisible.value = false
  ElMessage.success('标签添加成功')
}

/**
 * 编辑分类结果
 * @param {Object} result - 分类结果对象
 */
const editClassification = (result) => {
  // 显示编辑标签界面，这里我们简单地显示添加标签对话框
  showAddTagDialog(result)
}

/**
 * 确认分类
 * @param {Object} result - 分类结果对象
 */
const confirmClassification = (result) => {
  ElMessage.success(`文件"${result.fileName}"分类已确认`)
  // 在实际应用中，这里应该调用API保存分类结果
}
</script>

<style scoped>
.ai-classification {
  padding: 24px;
}

.upload-section {
  margin: 24px 0;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-area.is-dragging {
  border-color: #1890ff;
  background: #f0f7ff;
}

.upload-area.is-loading {
  cursor: wait;
}

.upload-area .icon {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.result-cards {
  display: grid;
  gap: 16px;
  margin-top: 24px;
}

.result-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.file-icon {
  font-size: 32px;
  margin-right: 16px;
}

.tags-section {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.delete-tag {
  margin-left: 4px;
  cursor: pointer;
  font-weight: bold;
}

.add-tag {
  width: 28px;
  height: 28px;
  border-radius: 14px;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-weight: bold;
}

.add-tag:hover {
  background: #e0e0e0;
}

.actions {
  display: flex;
  gap: 12px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
}

.edit-btn {
  background: #f0f0f0;
  color: #666;
}

.edit-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #1890ff;
  color: white;
}

.confirm-btn:hover {
  background: #0c80e1;
}
</style> 